package com.amway.qy.core.service.impl;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amway.qy.core.constants.QyWechatUrls;
import com.amway.qy.core.service.QyAccessTokenService;
import com.amway.qy.core.service.QyWechatServerInfoService;
import com.amway.qy.util.common.QyHttpClientUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

public class QyWechatServerInfoServiceImpl implements QyWechatServerInfoService {
	private static final Logger logger = LoggerFactory.getLogger(QyWechatServerInfoServiceImpl.class);
	
	private QyAccessTokenService accessTokenManager;
	
	public QyWechatServerInfoServiceImpl(QyAccessTokenService accessTokenManager){
		this.accessTokenManager = accessTokenManager;
	}
	
	@Override
	public List<String> getQyWechatSererIp() {
		logger.debug("getQyWechatSererIp() start.....");
		List<String> ipAddress = null;
		List<NameValuePair> paramsMap = new ArrayList<NameValuePair>();
		paramsMap.add(new BasicNameValuePair("access_token", accessTokenManager.getAccessToken()));
		String jsonString = QyHttpClientUtils.httpsGet(QyWechatUrls.GET_CALLBACK_IP,paramsMap);
		
		JsonObject jsonObject= new JsonParser().parse(jsonString).getAsJsonObject();
		if(jsonObject.has("ip_list")){
			Type listType = new TypeToken<List<String>>(){}.getType();
			ipAddress =  new Gson().fromJson(jsonObject.get("ip_list").getAsJsonArray().toString(),listType);
		}else{
			throw new IllegalStateException(jsonString);
		}		
		
		return ipAddress;
	}
	
	public QyAccessTokenService getAccessTokenManager() {
		return accessTokenManager;
	}

	public void setAccessTokenManager(QyAccessTokenService accessTokenManager) {
		this.accessTokenManager = accessTokenManager;
	}

	@Override
	public QyAccessTokenService getQyAccessTokenService() {
		// TODO Auto-generated method stub
		return accessTokenManager;
	}

	@Override
	public void setQyAccessTokenService(QyAccessTokenService tokenService) {
		this.accessTokenManager = tokenService;
	}
}
